package com.allen.webservice.jaxrs.utils;

import com.allen.webservice.jaxrs.domain.Student;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

public class CxfUtils {

    //xml schema
    public static final String XMLNS="xmlns=\"http://www.cdisc.org/ns/odm/v1.3\"" ;
    public static final String eCollect="xmlns:eCollect=\"http://www.trialos.com/edc/ns/odm\"";
    public static final String XSI="xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
    public static final String DS="xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"";
    public static final String SCHEMA_LOCATION = "xsi:schemaLocation=\"http://www.cdisc.org/ns/odm/v1.3 ODM1-3-2.xsd http://www.trialos.com/edc/ns/odm eCollect-ODM.xsd\"";


    /**
     * @description: json转对象
     * @param: [json, clazz]
     * @return: T
     */
    public static <T> T jsonToObject(String json, Class<T> clazz) throws JAXBException {
        final JAXBContext jaxbContext = CxfUtils.buildContext(clazz);
        final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return (T) unmarshaller.unmarshal(new StringReader(json));
    }


    public static <T> T jsonToObjectRemoveFlag(String json, Class<T> clazz) throws JAXBException {
        final JAXBContext jaxbContext = CxfUtils.buildContext(clazz);
        // 将xmlns声明去掉 在解析
        json = json.replace(XMLNS, "");
        json = json.replace(XSI, "");
        json = json.replace(DS, "");
        json = json.replace(SCHEMA_LOCATION, "");
        final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return (T) unmarshaller.unmarshal(new StringReader(json));
    }


    /**
     * @description: 获取jaxb上下文
     * @param: [clazz]
     * @return: javax.xml.bind.JAXBContext
     */
    public static <T> JAXBContext buildContext(Class<T> clazz) throws JAXBException {
        // 获取JAXB的上下文环境，需要传入具体的 Java bean -> 这里使用Student
        JAXBContext context = JAXBContext.newInstance(Student.class);
        return context;
    }
}
